<?php

class Crud_Form_Element_Column_Suggest extends Crud_Form_Element_Column
{
	public function init()
	{
		$element = $this->getElement();
		$element->setAttrib('class', 'element_suggest');
		
		$request = Zend_Controller_Front::getInstance()->getRequest();
		$table = $request->getParam('table');
		$id = $request->getParam('id', 0);
		$name = $this->getElement()->getName();
		$url = "/admin/crud/suggest/table/$table/id/$id/column/$name";
		$element->setAttrib('url', $url);
	}
	
	/**
	 * Get default value by row.
	 * 
	 * @param Crud_Section_Row
	 * @return void
	 */
	public function getRowValue(Crud_Section_Row $row = null)
	{
		$value = parent::getRowValue($row);
		
		if (is_numeric($value)) {
			$request = Zend_Controller_Front::getInstance()->getRequest();
			$table = $request->getParam('table');
			$section = AdminSectionPeer::getInstance()->fetchByKey($table);
			
			$element = $this->getElement();
			$element->setAttrib('table_id', $value);
			$name = $element->getName();
			
			$column = $section->getColumn($name);
			$fkTable = $column->getFkTable();
			$peer = $fkTable->getPeer();
			$row = $peer->find($value)->current();
			
			$column = $fkTable->getPrimaryFKColumn();
			$column = $section->getColumn($column);
			$getter = $column->getGetter();
			$value = $row->$getter();
		}
		
		return $value;
	}
	
	/**
	 * Return element class name by column type.
	 * Try to get class from config or automatic from column type.
	 * 
	 * @return string
	 */
	protected function _getElementClass()
	{
		return 'Zend_Form_Element';
	}
}